Exploring the Bitcoin Cryptocurrency Market

Originally a DataCamp Project in Python that I converted to R containing EDA about cryptocurrencies.
R
DataCamp
tidyverse
Published

May 31, 2024

Since the launch of Bitcoin in 2008, hundreds of similar projects based on the blockchain technology have emerged. We call these cryptocurrencies (also coins or cryptos in the Internet slang). Some are extremely valuable nowadays, and others may have the potential to become extremely valuable in the future. In fact, on the 6th of December of 2017, Bitcoin has a market capitalization above $200 billion.

1WARNING: The cryptocurrency market is exceptionally volatile2 and any money you put in might disappear into thin air. Cryptocurrencies mentioned here might be scams similar to Ponzi Schemes or have many other issues (overvaluation, technical, etc.). Please do not mistake this for investment advice.

2Update on March 2020: Well, it turned out to be volatile indeed*

That said, let’s get to business. We will start with a CSV we conveniently downloaded on the 6th of December of 2017 using the coinmarketcap API (NOTE: The public API went private in 2020 and is no longer available) named datasets/coinmarketcap_06122017.csv.

Originally a DataCamp Python project that I converted to R.

# Reading datasets/coinmarketcap_06122017.csv
dec6 = read_csv('datasets/coinmarketcap_06122017.csv')

# Selecting the 'id' and the 'market_cap_usd' columns
market_cap_raw <- dec6 %>% select(id, market_cap_usd)

# Counting the number of values
count(market_cap_raw)
# Inspecting the data
head(market_cap_raw)

1 Discard the cryptocurrencies without a market capitalization

Why do the count() for id and market_cap_usd differ above? It is because some cryptocurrencies listed in coinmarketcap.com have no known market capitalization, this is represented by NaN in the data, and NaNs are not counted by count(). These cryptocurrencies are of little interest to us in this analysis, so they are safe to remove.

# Filtering out rows without a market capitalization
cap <- market_cap_raw %>% filter(market_cap_usd > 0)

# Counting the number of values again
count(cap)

2 How big is Bitcoin compared with the rest of the cryptocurrencies?

At the time of writing, Bitcoin is under serious competition from other projects, but it is still dominant in market capitalization. Let’s plot the market capitalization for the top 10 coins as a barplot to better visualize this.

# Declaring these now for later use in the plots
TOP_CAP_TITLE <- 'Top 10 market capitalization'
TOP_CAP_YLABEL <- '% of total cap'

# Selecting the first 10 rows and calculating market_cap_perc
cap10 <- cap %>%
    arrange(desc(market_cap_usd)) %>%
    mutate(market_cap_perc = market_cap_usd * 100 / sum(market_cap_usd)) %>%
    head(n = 10)

# Ordering the percentages
cap10 <- cap10 %>% mutate(id = fct_reorder(id, desc(market_cap_perc)))

# Plotting the barplot with the title defined above 
cap10 %>% ggplot(aes(id, market_cap_perc)) + 
  geom_col() + 
  labs(title = TOP_CAP_TITLE, y = TOP_CAP_YLABEL) +
  scale_y_continuous(breaks = seq(0, 100, by = 10)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1),
        axis.title.x = element_blank())

3 Making the plot easier to read and more informative

While the plot above is informative enough, it can be improved. Bitcoin is too big, and the other coins are hard to distinguish because of this. Instead of the percentage, let’s use a log10 scale of the “raw” capitalization. Plus, let’s use color to group similar coins and make the plot more informative1.

For the colors rationale: bitcoin-cash and bitcoin-gold are forks of the bitcoin blockchain2.

Ethereum and Cardano both offer Turing Complete smart contracts. Iota and Ripple are not minable. Dash, Litecoin, and Monero get their own color.

1This coloring is a simplification. There are more differences and similarities that are not being represented here.

2The bitcoin forks are actually very different, but it is out of scope to talk about them here. Please see the warning above and do your own research.

# Colors for the bar plot
COLORS <- c('orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'gray', 'orange', 'red', 'green')

# Plotting market_cap_usd as before but adding the colors and scaling the y-axis  
cap10 %>% ggplot(aes(id, market_cap_usd)) + 
  geom_col(fill = COLORS) + 
  scale_y_log10(labels = scales::label_log(digits = 2)) +
  labs(title = TOP_CAP_TITLE, y = "log(USD)") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1),
        axis.title.x = element_blank())

4 What is going on?! Volatility in cryptocurrencies

The cryptocurrencies market has been spectacularly volatile since the first exchange opened. This notebook didn’t start with a big, bold warning for nothing. Let’s explore this volatility a bit more! We will begin by selecting and plotting the 24 hours and 7 days percentage change, which we already have available.

# Selecting the id, percent_change_24h and percent_change_7d columns
volatility <- dec6 %>% select(id, percent_change_24h, percent_change_7d)

# Dropping all NaN rows
volatility <- volatility %>% drop_na()

# Sorting the DataFrame by percent_change_24h in ascending order
volatility <- volatility %>% arrange(percent_change_24h)

# Checking the first few rows
head(volatility)

5 Well, we can already see that things are a bit crazy

It seems you can lose a lot of money quickly on cryptocurrencies. Let’s plot the top 10 biggest gainers and top 10 losers in market capitalization.

# Defining a function with 2 parameters, the series to plot and the title
top10_subplot <- function(volatility_series, percent_change_col, title) {
    
    # Plotting the barchart for the top 10 losers
    top10_losers <- head(volatility_series, 10)
    p1 <- top10_losers %>%
        ggplot(aes(x = reorder(id, !!sym(percent_change_col)), y = !!sym(percent_change_col))) +
        geom_bar(stat = "identity", fill = "darkred") +
        labs(y = "% Change") +
        theme(axis.text.x = element_text(angle = 45, hjust = 1),
              axis.title.x = element_blank())
        
    # Plotting the barchart for the top 10 winners
    top10_winners <- tail(volatility_series, 10)
    p2 <- top10_winners %>%
        ggplot(aes(x = reorder(id, !!sym(percent_change_col)), y = !!sym(percent_change_col))) +
        geom_bar(stat = "identity", fill = "darkblue") +
        theme(axis.text.x = element_text(angle = 45, hjust = 1),
              axis.title.x = element_blank(),
              axis.title.y = element_blank())
    
    # Combining the two side by side plots
    g = (p1 + p2) + 
      plot_annotation(title)
    
    # Disabling the return value NULL
    return(g)
}

DTITLE <- "24 hours top losers and winners"

# Calling the function above with the 24 hours period series and title DTITLE
vol_series <- volatility %>% arrange(percent_change_24h)
top10_subplot(vol_series, "percent_change_24h", DTITLE)

6 Ok, those are… interesting. Let’s check the weekly Series too.

800% daily increase?! Why are we doing this tutorial and not buying random coins?1

After calming down, let’s reuse the function defined above to see what is going weekly instead of daily.

1Please take a moment to understand the implications of the red plots on how much value some cryptocurrencies lose in such short periods of time

# Sorting in ascending order
volatility7d <- volatility %>% arrange(percent_change_7d)

WTITLE <- "Weekly top losers and winners"

# Calling the top10_subplot function
top10_subplot(volatility7d, "percent_change_7d", WTITLE)

7 How small is small?

The names of the cryptocurrencies above are quite unknown, and there is a considerable fluctuation between the 1 and 7 days percentage changes. As with stocks, and many other financial products, the smaller the capitalization, the bigger the risk and reward. Smaller cryptocurrencies are less stable projects in general, and therefore even riskier investments than the bigger ones1. Let’s classify our dataset based on Investopedia’s capitalization definitions for company stocks.

1Cryptocurrencies are a new asset class, so they are not directly comparable to stocks. Furthermore, there are no limits set in stone for what a “small” or “large” stock is. Finally, some investors argue that bitcoin is similar to gold, this would make them more comparable to a commodity instead.

# Selecting everything bigger than 10 billion 
largecaps <- cap %>% filter(market_cap_usd > 1e+10)

# Printing out largecaps
largecaps

8 Most coins are tiny

These are the market cap definitions from Investopedia:

  • Large cap: +10 billion
  • Mid cap: 2 billion - 10 billion
  • Small cap: 300 million - 2 billion
  • Micro cap: 50 million - 300 million
  • Nano cap: Below 50 million

Note that many coins are not comparable to large companies in market cap, so let’s divert from the original Investopedia definition by merging categories.

# Defining a function for counting different market caps from the "cap" DataFrame
capcount <- function(filter_string) {
  return(nrow(filter(cap, !!rlang::parse_expr(filter_string))))
}

# Labels for the plot
LABELS <- c("biggish", "micro", "nano")

# Using capcount to count the not_so_small cryptos
biggish <- capcount("market_cap_usd > 3e+8")

# Same as above for micro ...
micro <- capcount("market_cap_usd >= 5e+7 & market_cap_usd < 3e+8")

# ... and for nano
nano <- capcount("market_cap_usd < 5e+7")

# Making a list with the 3 counts
values <- c(biggish, micro, nano)

# Creating a data frame for plotting
df <- data.frame(Category = LABELS, Count = values)

# Plotting them with ggplot2
ggplot(df, aes(x = Category, y = Count)) +
  geom_bar(stat = "identity") +
  labs(title = "Market Cap Distribution", x = "Category", y = "Count")